<template>
  <div class="cu-common-layout">
    <div class="cu-common-layout-center">
      <el-row class="cu-common-search-box" :gutter="16">
        <el-form @submit.native.prevent>
          <el-col :span="6">
            <el-form-item label="师训项目">
              <el-input v-model="query.trainId" placeholder="师训项目" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="报名校区">
              <el-select v-model="query.campusId" placeholder="报名校区" filterable clearable>
                <el-option v-for="(item, index) in campusOptions" :key="index" :label="item.fullName" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="报名老师">
              <el-input v-model="query.teacherName" placeholder="报名老师" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="订单号">
              <el-input v-model="query.id" placeholder="订单号" clearable />
            </el-form-item>
          </el-col>
          <template v-if="showAll">
            <el-col :span="6">
              <el-form-item label="报名时间">
                <el-date-picker v-model="query.createTime" type="daterange" :picker-options="pickerOptions" value-format="yyyy-MM-dd" start-placeholder="开始日期" end-placeholder="结束日期" clearable :editable="false"></el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="付款时间">
                <el-date-picker v-model="query.payTime" type="daterange" :picker-options="pickerOptions" value-format="yyyy-MM-dd" start-placeholder="开始日期" end-placeholder="结束日期" clearable :editable="false"></el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="支付单号">
                <el-input v-model="query.payOrderCode" placeholder="支付单号" clearable />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="支付状态">
                <el-select v-model="query.payStatus" placeholder="请选择" clearable multiple>
                  <el-option v-for="item in payStatusOptions" :key="item.enCode" :label="item.fullName" :value="item.enCode"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="订单来源">
                <el-select v-model="query.source" placeholder="请选择" clearable>
                  <el-option v-for="item in sourceOptions" :key="item.enCode" :label="item.fullName" :value="item.enCode"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </template>
          <el-col :span="6">
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" @click="search()" native-type="submit">{{ $t('common.search') }}</el-button>
              <el-button icon="el-icon-refresh-right" @click="reset()">{{ $t('common.reset') }}</el-button>
              <el-button type="text" icon="el-icon-arrow-down" @click="showAll = true" v-if="!showAll">展开</el-button>
              <el-button type="text" icon="el-icon-arrow-up" @click="showAll = false" v-else>收起</el-button>
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
      <div class="cu-common-layout-main cu-flex-main">
        <div class="cu-common-head">
          <div>
            <!-- <el-button type="primary" icon="el-icon-plus" @click="addOrUpdateHandle()" v-has="'btn_add'">新增</el-button> -->
            <el-button v-has="'btn_download'" type="text" icon="el-icon-download" @click="exportData()">导出</el-button>
          </div>
          <div class="cu-common-head-right">
            <el-tooltip effect="dark" content="刷新" placement="top">
              <el-link icon="icon-ym icon-ym-Refresh cu-common-head-icon" :underline="false" @click="reset()" />
            </el-tooltip>
            <screenfull isContainer />
          </div>
        </div>
        <custom-table v-loading="listLoading" :data="list" @sort-change="sortChange">
          <el-table-column prop="id" label="订单号" align="center" v-if="custom.hasP('id')" width="150" />
          <el-table-column prop="orderTitle" label="订单名称" align="left" v-if="custom.hasP('orderTitle')" show-overflow-tooltip></el-table-column>
          <el-table-column prop="campusId" label="校区名称" align="left" v-if="custom.hasP('campusId')" width="200" show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.campusId | dynamicText(campusOptions) }}
            </template>
          </el-table-column>
          <el-table-column prop="campusStatusText" label="校区状态" align="center" v-if="custom.hasP('campusStatusText')" width="80" />
          <el-table-column prop="levelText" label="校区阶段" align="center" v-if="custom.hasP('levelText')" width="80" />
          <el-table-column prop="source" label="订单来源" align="center" v-if="custom.hasP('source')" width="100">
            <template slot-scope="scope">
              {{ scope.row.source | dynamicCodeText(sourceOptions) }}
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="报名时间" align="center" v-if="custom.hasP('createTime')" :formatter="custom.tableDateTimeFormat" width="120" />
          <!-- <el-table-column prop="orderAmount" label="订单金额" align="right" v-if="custom.hasP('orderAmount')" width="70" /> -->
          <el-table-column prop="statusText" label="订单状态" align="center" v-if="custom.hasP('statusText')" width="80" />
          <el-table-column prop="payTime" label="付款时间" align="center" v-if="custom.hasP('payTime')" :formatter="custom.tableDateTimeFormat" width="120" />
          <el-table-column prop="refundAmount" label="抵扣金额" align="center" v-if="custom.hasP('refundAmount')" width="80">
            <template slot-scope="scope">
              <el-tooltip v-if="!!scope.row.deductionAmount" class="item" effect="dark" :content="scope.row.deductionMemo" placement="top">
                <el-button type="text">{{ scope.row.deductionAmount }}</el-button>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column prop="payAmount" label="支付金额" align="right" v-if="custom.hasP('payAmount')" width="70" />

          <el-table-column prop="itemNum" label="报名人数" align="left" v-if="custom.hasP('itemNum')" width="80" />
          <el-table-column prop="memo" label="报名老师" align="left" v-if="custom.hasP('memo')" show-overflow-tooltip />
          <el-table-column prop="refundAmount" label="退款金额" align="center" v-if="custom.hasP('refundAmount')" width="80">
            <template slot-scope="scope">
              <span v-if="scope.row.refundAmount > 0" style="color: red">
                {{ scope.row.refundAmount }}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="操作" fixed="right" width="190" align="center">
            <template slot-scope="scope">
              <el-button type="text" size="mini" v-has="'btn_detail'" @click="addOrUpdateHandle(scope.row.id, true)">详细</el-button>
              <el-button type="text" size="mini" v-has="'btn_refund'" :disabled="scope.row.payStatus == 'Refunded' || scope.row.status != 'Normal' || (scope.row.payAmount == scope.row.refundAmount && scope.row.payAmount > 0)" @click="refundOrUpdateHandle(scope.row.id, true)" class="cu-table-delBtn">退费</el-button>
              <el-button type="text" size="mini" v-has="'btn_remove'" @click="handleDel(scope.row.id)" class="cu-table-delBtn">删除</el-button>
            </template>
          </el-table-column>
        </custom-table>
        <pagination :total="total" :page.sync="listQuery.currentPage" :limit.sync="listQuery.pageSize" @pagination="initData" />
      </div>
    </div>
    <custom-form v-if="formVisible" ref="CustomForm" @refresh="refresh" />
    <export-box v-if="exportBoxVisible" ref="ExportBox" @download="download" />
    <refund-form v-if="refundFormVisible" ref="RefundForm" @refresh="search" />
  </div>
</template>
<script>
import request from '@/utils/request'
import { getDictionaryDataSelector } from '@/api/systemData/dictionary'
import CustomForm from './Form'
import RefundForm from './Refund/index.vue'
import custom from '@/utils/custom'
import ExportBox from './ExportBox'
import { getCampusSelector } from '@/api/campus/campus'
import { getTrainSelector } from '@/api/campus/train'
// import { previewDataInterface } from '@/api/systemData/dataInterface'
export default {
  name: 'train_order',
  components: { CustomForm, ExportBox, RefundForm },
  data() {
    return {
      showAll: false,
      query: {
        trainId: undefined,
        campusId: undefined,
        createTime: [],
        payOrderCode: undefined,
        payStatus: undefined,
        payTime: [],
        orderType: 'train',
        id: '',
        teacherName: undefined
      },
      list: [],
      listLoading: true,
      multipleSelection: [],
      total: 0,
      listQuery: {
        currentPage: 1,
        pageSize: 20,
        sort: 'desc',
        sidx: ''
      },
      formVisible: false,
      exportBoxVisible: false,
      refundFormVisible: false,
      columnList: [{ prop: 'id', label: '订单号' }, { prop: 'shortName', label: '校区名称' }, { prop: 'campusStatusText', label: '校区状态' }, { prop: 'levelText', label: '校区阶段' }, { prop: 'orderTitle', label: '订单名称' }, { prop: 'createTime', label: '下单时间' }, { prop: 'statusText', label: '订单状态' }, { prop: 'memo', label: '订单备注' }, { prop: 'paymentCodeText', label: '支付方式' }, { prop: 'payTime', label: '支付时间' }, { prop: 'payAmount', label: '支付金额' }, { prop: 'payMethodText', label: '支付方式' }, { prop: 'refundAmount', label: '退款金额' }],
      paymentsTypeOptions: [],
      orderStatusOptions: [],
      payStatusOptions: [],
      campusOptions: [],
      trainOptions: [],
      sourceOptions: [{ enCode: '贝尔校长云', text: '贝尔校长云' }, { enCode: '线下报名', text: '线下报名' }],
      pickerOptions: {
        shortcuts: [
          {
            text: '最近一周',
            onClick(picker) {
              const today = new Date()
              let daterange = custom.getLastWeekDays(today, 1)
              picker.$emit('pick', [new Date(daterange.starttime), today])
            }
          },
          {
            text: '最近一个月',
            onClick(picker) {
              const today = new Date()
              let daterange = custom.getLastMonthDays(today, 1)
              picker.$emit('pick', [new Date(daterange.starttime), today])
            }
          },
          {
            text: '最近三个月',
            onClick(picker) {
              const today = new Date()
              let daterange = custom.getLastMonthDays(today, 3)
              picker.$emit('pick', [new Date(daterange.starttime), today])
            }
          }
        ]
      }
    }
  },
  watch: {
    '$route.query.title': {
      handler(newVal) {
        this.query.trainId = newVal
        this.initData();
      }
    }
  },
  computed: {},
  async created() {
    let title = this.$route.query.title ? this.$route.query.title : ''
    if (!!title) {
      this.query.trainId = this.$route.query.title
    }
    await this.defaultDate()
    this.initData()
    this.getPaymentsTypeOptions()
    this.getOrderStatusOptions()
    this.getPayStatusOptions()
    getCampusSelector().then(res => {
      this.campusOptions = res.data
    })
    getTrainSelector().then(res => {
      this.trainOptions = res.data
    })
  },
  methods: {
    getPaymentsTypeOptions() {
      this.$store.dispatch('base/getDictionaryData', { sort: 'PaymentsType' }).then(res => {
        this.paymentsTypeOptions = res
      })
    },
    getOrderStatusOptions() {
      this.$store.dispatch('base/getDictionaryData', { sort: 'OrderStatus' }).then(res => {
        this.orderStatusOptions = res
      })
    },
    getPayStatusOptions() {
      this.$store.dispatch('base/getDictionaryData', { sort: 'PayStatus' }).then(res => {
        this.payStatusOptions = res
      })
    },
    sortChange({ column, prop, order }) {
      this.listQuery.sort = order == 'ascending' ? 'asc' : 'desc'
      this.listQuery.sidx = !order ? '' : prop
      this.initData()
    },

    initData() {
      this.listLoading = true
      let _query = {
        ...this.listQuery,
        ...this.query
      }
      let query = {}
      for (let key in _query) {
        if (Array.isArray(_query[key])) {
          query[key] = _query[key].join()
        } else {
          query[key] = _query[key]
        }
      }
      request({
        url: `/api/train/order`,
        method: 'GET',
        data: query
      }).then(res => {
        this.list = res.data.list
        this.total = res.data.pagination.total
        this.listLoading = false
      })
    },
    handleDel(id) {
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        type: 'warning'
      })
        .then(() => {
          request({
            url: `/api/train/order/${id}`,
            method: 'DELETE'
          }).then(res => {
            this.$message({
              type: 'success',
              message: res.msg,
              onClose: () => {
                this.initData()
              }
            })
          })
        })
        .catch(() => {})
    },
    addOrUpdateHandle(id, isDetail) {
      this.formVisible = true
      this.$nextTick(() => {
        this.$refs.CustomForm.init(id, isDetail)
      })
    },
    refundOrUpdateHandle(id) {
      this.refundFormVisible = true
      this.$nextTick(() => {
        this.$refs.RefundForm.init(id)
      })
    },
    exportData() {
      this.exportBoxVisible = true
      this.$nextTick(() => {
        this.$refs.ExportBox.init(this.columnList)
      })
    },
    download(data) {
      let _query = { ...data, ...this.listQuery, ...this.query }
      let query = {}
      for (let key in _query) {
        if (Array.isArray(_query[key])) {
          query[key] = _query[key].join()
        } else {
          query[key] = _query[key]
        }
      }

      request({
        url: `/api/train/order/Actions/Export`,
        method: 'GET',
        data: query
      }).then(res => {
        this.$message({
          message: '文件下载链接稍后推送到站内信，请在右上角铃铛图标处查收！',
          type: 'success',
          showClose: true,
          duration: 0
        })
        this.$refs.ExportBox.visible = false
        this.exportBoxVisible = false
      })
    },
    search() {
      this.listQuery = {
        currentPage: 1,
        pageSize: 50,
        sort: 'desc',
        sidx: ''
      }
      this.initData()
    },
    refresh(isrRefresh) {
      this.formVisible = false
      if (isrRefresh) this.reset()
    },
    reset() {
      for (let key in this.query) {
        this.query[key] = undefined
      }
      this.listQuery = {
        currentPage: 1,
        pageSize: 50,
        sort: 'desc',
        sidx: ''
      }
      this.defaultDate()
      this.initData()
    },
     defaultDate() {
      //获取新的时间(2019.4.12）
      let today = new Date()
      //加1天
      var date = new Date(today.setDate(today.getDate() + 1))
      let daterange = custom.getLastMonthDays(today, 1)
      this.query.createTime = [daterange.starttime, custom.dateFormat(date, 'YYYY-MM-DD')] //将值设置给插件绑定的数据
      //this.startTime =beg;
      //this.endTime=end;
    }
  }
}
</script>
